package com.dd.seckill.cluster.config.redis.lua;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/8 10:46
 * @Description Lua脚本预加载
 */
@Slf4j
@Component
public class RedisScriptPreLoader {

    @Value("classpath:lua/seckill.lua")
    private Resource seckillScript;

    @Getter
    private String seckillScriptSha1;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostConstruct
    public void init() {
        // 预加载Lua脚本并获取SHA1值
        try {
            String scriptContent = StreamUtils.copyToString(seckillScript.getInputStream(), StandardCharsets.UTF_8);
            this.seckillScriptSha1 = redisTemplate.execute((RedisCallback<String>) connection ->
                    connection.scriptLoad(scriptContent.getBytes())
            );
            log.info("Seckill Lua script loaded successfully, SHA1: {}", seckillScriptSha1);
        } catch (IOException e) {
            log.error("Failed to load seckill Lua script", e);
            throw new RuntimeException("Failed to load seckill Lua script", e);
        }
    }
}